package com.example.blog_system.service.impl;

import com.example.blog_system.dao.ArticleMapper;
import com.example.blog_system.dao.StatisticMapper;
import com.example.blog_system.model.domain.Article;
import com.example.blog_system.model.domain.Statistic;
import com.example.blog_system.service.IArticleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
//import com.sun.org.glassfish.external.statistics.Statistic;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Article selectArticleWithId(Integer id) {
        Article article = articleMapper.selectArticleWithId(id);
        return article;
    }

    @Override
    public void publish(Article article) {
        article.setContent(EmojiParser.parseToAliases(article.getContent()));
        article.setCreated(new Date());
        article.setHits(0);
        article.setCommentsNum(0);
        //  插入文章，同时插入文章数据
        articleMapper.publishArticle(article);
        statisticMapper.addStatistic(article);
    }

    @Autowired
    private StatisticMapper statisticMapper;

    @Override
    public PageInfo<Article> selectArticleWithPage(Integer page, Integer count) {
        PageHelper.startPage(page,count);
        List<Article> articleList = articleMapper.selectArticleWithPage();
        for (int i=0;i<articleList.size();i++){
            Article article = articleList.get(i);
            Statistic statistic = statisticMapper.selectStatisticWithArticleId(article.getId());
            article.setHits(statistic.getHits());
            article.setCommentsNum(statistic.getCommentsNum());
        }
        PageInfo<Article> pageInfo = new PageInfo<>(articleList);
        return pageInfo;
    }

    @Override
    public List<Article> getHeatArticles() {
        List<Statistic> list = statisticMapper.getStatistic();
        List<Article> articleList = new ArrayList<>();
        for (int i=0;i<list.size();i++){
            Article article = articleMapper.selectArticleWithId(list.get(i).getArticleId());
            article.setHits(list.get(i).getHits());
            article.setCommentsNum(list.get(i).getCommentsNum());
            articleList.add(article);
            if (i>=9){
                break;
            }
        }
        return articleList;
    }
}
